//
//  CalendarView.m
//  ProjectSource_Demo
//
//  Created by Liu on 16/3/19.
//  Copyright © 2016年 AngryBear. All rights reserved.
//

#import "CalendarView.h"

#define Calendar_Days 7*5

@interface CalendarCell : UICollectionViewCell

@property (nonatomic, strong) UILabel *textLabel;

@end

@interface CalendarView ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
{
    UICollectionView *_currentCollectView;
    UICollectionView *_reuseCollectionView;

    NSInteger _currentIndex;
    NSArray *_currentCollectionData;
    NSArray *_reuseCollectionData;
    NSDate *_currentDate;
    NSDate *_reuseDate;
    NSDate *_selectedDate;
    NSDateFormatter *_dateFormatter;
    NSCalendar *_calendar;
    NSCalendarUnit _calendarUnit;
}
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *backgroundImageView;

@property (nonatomic, strong) NSString *stringOfSlectedDate;

@end

@implementation CalendarView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor blackColor];
        [self addSubview:self.backgroundImageView];
        [self addSubview:self.scrollView];
        
        _calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        _calendarUnit = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitYear;
        
        [self addCollectionViews];
    }
    return self;
}


#pragma mark - Calendar Caculate
- (NSArray *)calendarArrayWithDate:(NSDate *)date
{
    NSMutableArray *array = [NSMutableArray array];
    NSDateComponents *components = [_calendar components:_calendarUnit fromDate:date];
    NSDate *firstDayDate = [self dateOfMonths:0 days:-components.day fromDate:date];
    NSDateComponents *firstDayComponents = [_calendar components:_calendarUnit fromDate:firstDayDate];
    
    NSInteger weekday = firstDayComponents.weekday - 1; //从星期一开始算起
    NSInteger original = components.day + weekday;
    for (NSInteger i = 1; i <= Calendar_Days; i++) {
        NSInteger day = -original + i;
        NSDate *item = [self dateOfMonths:0 days:day fromDate:date];
        [array addObject:item];
    }
    
    return array;
}

- (NSDate *)dateOfMonths:(NSInteger)months days:(NSInteger)days fromDate:(NSDate *)date
{
    NSDateComponents *lastMonthComponnets = [[NSDateComponents alloc] init];
    lastMonthComponnets.month = months;
    lastMonthComponnets.day = days;
    NSDate *lastDate = [_calendar dateByAddingComponents:lastMonthComponnets toDate:date options:NSCalendarMatchStrictly];
    return lastDate;
}

#pragma mark - Public Methods
- (void)setBackgroundImage:(UIImage *)image
{
    self.backgroundImageView.image = image;
}

#pragma mark - Private Methods
- (void)addCollectionViews
{
    for (int i = 0; i < 2; i++) {
        CGFloat space = (CGRectGetWidth(self.bounds) - 7*26)/8;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(26, 26);
        flowLayout.minimumLineSpacing = 8;
        flowLayout.minimumInteritemSpacing = space;
        flowLayout.sectionInset = UIEdgeInsetsMake(8, space, 8, space);
        
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.scrollView.bounds collectionViewLayout:flowLayout];
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.tag = 100 + i;
        collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        
        [collectionView registerClass:[CalendarCell class] forCellWithReuseIdentifier:NSStringFromClass([CalendarCell class])];
        
        if (i == 0) {
            CGRect frame = collectionView.frame;
            frame.origin.x = CGRectGetWidth(self.scrollView.bounds);
            collectionView.frame = frame;
            [self.scrollView addSubview:collectionView];
            _currentCollectView = collectionView;
            [self currentCollectionReloadData];
        }
        else {
            _reuseCollectionView = collectionView;
        }
    }
    
    self.scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.bounds)*3, CGRectGetHeight(self.bounds));
    [self.scrollView setContentOffset:CGPointMake(CGRectGetWidth(self.bounds), 0)];
}

- (void)currentCollectionReloadData
{
    _currentCollectionData = [self calendarArrayWithDate:self.selectedDate];
    [_currentCollectView reloadData];
}

- (void)reuseCollectionReloadDataWithDate:(NSDate *)date
{
    _reuseCollectionData = [self calendarArrayWithDate:date];
    [_reuseCollectionView reloadData];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return Calendar_Days;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([CalendarCell class]) forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    
    NSDate *date;
    if (collectionView == _currentCollectView) {
        date = [_currentCollectionData objectAtIndex:indexPath.row];
    }
    else {
        date = [_reuseCollectionData objectAtIndex:indexPath.row];
    }

    NSDateComponents *dateComponents = [_calendar components:_calendarUnit fromDate:date];
    NSDateComponents *selectedDate = [_calendar components:_calendarUnit fromDate:self.selectedDate];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%ld", dateComponents.day];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor colorWithHexRGB:0x333333];
    
    if (selectedDate.month == dateComponents.month && selectedDate.day == dateComponents.day && selectedDate.year == dateComponents.year) {
        cell.textLabel.backgroundColor = [UIColor colorWithHexRGB:0x0091cd];
        CGRect frame = cell.frame;
        frame.origin.y -= 12;
        frame.size.height += 24;
        self.selectedItemRect = frame;
    }
    if (selectedDate.month == dateComponents.month) {
        cell.textLabel.textColor = [UIColor colorWithWhite:1.0 alpha:0.5];
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (collectionView == _currentCollectView) {
        NSDate *date = [_currentCollectionData objectAtIndex:indexPath.row];
        self.selectedDate = date;
        [self currentCollectionReloadData];
    }
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _currentIndex = scrollView.contentOffset.x/scrollView.bounds.size.width;
    CGFloat x = [scrollView.panGestureRecognizer translationInView:scrollView].x;
    if (x > 0) {    //scroll left
        CGRect frame = _currentCollectView.frame;
        frame.origin.x -= frame.size.width;
        _reuseCollectionView.frame = frame;
        [scrollView addSubview:_reuseCollectionView];
        
        _reuseDate = [self dateOfMonths:-1 days:0 fromDate:_currentDate];
        [self reuseCollectionReloadDataWithDate:_reuseDate];
    }
    else {  //scroll right
        CGRect frame = _currentCollectView.frame;
        frame.origin.x += frame.size.width;
        _reuseCollectionView.frame = frame;
        [scrollView addSubview:_reuseCollectionView];
        
        _reuseDate = [self dateOfMonths:1 days:0 fromDate:_currentDate];
        [self reuseCollectionReloadDataWithDate:_reuseDate];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x/scrollView.bounds.size.width;
    if (index != _currentIndex) {
        UICollectionView *temp = _reuseCollectionView;
        _reuseCollectionView = _currentCollectView;
        _currentCollectView = temp;
        
        _currentDate = _reuseDate;
        CGRect frame = _currentCollectView.frame;
        frame.origin.x = frame.size.width;
        _currentCollectView.frame = frame;
        [self.scrollView setContentOffset:CGPointMake(CGRectGetWidth(frame), 0)];
    }
}

#pragma mark - Setter Methods
- (void)setSelectedDate:(NSDate *)selectedDate
{
    _selectedDate = selectedDate;
    _currentDate = selectedDate;

    if (_dateFormatter == nil) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    
    _dateFormatter.dateFormat = self.dateFormat;
    self.stringOfSlectedDate = [_dateFormatter stringFromDate:self.selectedDate];
}

#pragma mark - Getter Methods
- (UIImageView *)backgroundImageView
{
    if (_backgroundImageView == nil) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _backgroundImageView.backgroundColor = [UIColor clearColor];
        _backgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    }
    return _backgroundImageView;
}

- (UIScrollView *)scrollView
{
    if (_scrollView == nil) {
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        scrollView.backgroundColor = [UIColor clearColor];
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.delegate = self;
        scrollView.pagingEnabled = YES;
        scrollView.bounces = NO;
        _scrollView = scrollView;
    }
    return _scrollView;
}

- (NSDate *)selectedDate
{
    if (_selectedDate == nil) {
        _selectedDate = [NSDate date];
    }
    return _selectedDate;
}

- (NSString *)dateFormat
{
    if (_dateFormat == nil) {
        _dateFormat = @"yyyy-MM-dd";
    }
    return _dateFormat;
}

@end



@implementation CalendarCell

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.textLabel];
    }
    return self;
}

#pragma mark - Getter Methods
- (UILabel *)textLabel
{
    if (_textLabel == nil) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 26, 26)];
        label.backgroundColor = [UIColor clearColor];
        label.numberOfLines = 1;
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:16];
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 13.0f;
        label.layer.masksToBounds = YES;
        _textLabel = label;
    }
    return _textLabel;
}

@end